package cn.edu.hit.kg.data;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.*;

/**
 * Created by Wang on 2018/11/13.
 */
public class NodeImpl implements Node, Serializable {
    private long id;
    private Set<String> labels = new HashSet<>();
    private Map<String, Object> valueMap = new HashMap<>();

    protected static ObjectMapper mapper = new ObjectMapper();

    @Override
    public long id() {
        return id;
    }

    @Override
    public Map<String, Object> asMap() {
        return valueMap;
    }

    @Override
    public Iterable<String> labels() {
        return labels;
    }

    @Override
    public boolean hasLabel(String label) {
        return labels.contains(label);
    }

    public void setId(long id) {
        this.id = id;
    }

    public void setLabels(Set<String> labels) {
        this.labels = labels;
    }

    public void setValueMap(Map<String, Object> valueMap) {
        this.valueMap = new HashMap<>();
        if (valueMap != null) {
            valueMap.forEach((k, v) -> {
                if (v instanceof String) {
                    this.valueMap.put(k, stringTransfer(v));
                } else {
                    this.valueMap.put(k, v);
                }
            });
        }
    }

    public static String stringTransfer(Object v) {
        String rawStr = v.toString();
        rawStr = unescapeText(rawStr);
        return StringUtils.strip(rawStr, "\"");
    }

    public static String unescapeText(String text) {
        return text.replaceAll("\\\\\"", "\"");
    }

    public long getId() {
        return id;
    }

    public Set<String> getLabels() {
        return labels;
    }

    public Map<String, Object> getValueMap() {
        return valueMap;
    }

    @Override
    public String toString() {
        try {
            return mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    @Override
    public Object get(String key) {
        return this.valueMap.get(key);
    }
}
